package tree;

import java.util.ArrayList;
import java.util.List;

public class CommonMethod {

    public static void printTree(TreeNode root) {
        if (root == null) {
            System.out.println("Tree is empty");
            return;
        }

        // 获取树的深度
        int depth = getDepth(root);
        // 计算最后一层的节点数（最大宽度）
        int width = (int) Math.pow(2, depth - 1);

        // 初始化一个二维列表来存储节点和连接线
        List<List<String>> levels = new ArrayList<>();
        for (int i = 0; i < depth; i++) {
            levels.add(new ArrayList<>());
            for (int j = 0; j < width; j++) {
                levels.get(i).add(" ");
            }
        }

        // 递归填充节点和连接线
        fillTree(root, levels, 0, 0, width - 1);

        // 打印树
        for (List<String> level : levels) {
            for (String s : level) {
                System.out.print(s);
            }
            System.out.println();
        }
    }

    private static void fillTree(TreeNode node, List<List<String>> levels, int level, int left, int right) {
        if (node == null) return;

        int mid = (left + right) / 2;
        levels.get(level).set(mid, String.valueOf(node.val));

        if (level + 1 < levels.size()) {
            // 添加连接线
            if (node.left != null) {
                int leftMid = (left + mid - 1) / 2;
                for (int i = leftMid + 1; i < mid; i++) {
                    levels.get(level + 1).set(i, "-");
                }
                levels.get(level + 1).set(leftMid, "/");
            }

            if (node.right != null) {
                int rightMid = (mid + 1 + right) / 2;
                for (int i = mid + 1; i < rightMid; i++) {
                    levels.get(level + 1).set(i, "-");
                }
                levels.get(level + 1).set(rightMid, "\\");
            }
        }

        // 递归处理左右子树
        fillTree(node.left, levels, level + 2, left, mid - 1);
        fillTree(node.right, levels, level + 2, mid + 1, right);
    }

    private static int getDepth(TreeNode node) {
        if (node == null) return 0;
        return 1 + Math.max(getDepth(node.left), getDepth(node.right));
    }
}
